﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using AutoFacUtils;
using FluentValidation;
using CashFlow.Web.Common;
using CashFlow.Web.Def;
using CashFlow.Web.Areas.ShopManage.Models.Order;
using CashFlow.Web.Areas.ShopManage.Service;
using IUserService2 = CashFlow.Web.Service.IUserService;

namespace CashFlow.Web.Areas.ShopManage.Validator.Order
{
    public class UpdateOrderModelValidator
        : AbstractValidator<UpdateOrderModel>
    {
        private IOrderService GetOrderService() { return AutoFacHelper.Get<IOrderService>(); }
        private IUserService2 GetIUserService2() { return AutoFacHelper.Get<IUserService2>(); }

        public UpdateOrderModelValidator()
        {
            CascadeMode = CascadeMode.Stop;
            RuleFor(x => x.OrderId).Must(x => IsOrderIdValiad(x))
                .WithMessage("非法OrderId");
            RuleFor(x => x.BuyerUserId).Must((x, y) =>
            {
                if (CommonValidator.IsUserInShop(y)
                    && x.BuyerUserId != x.SellerUserId)

                {
                    return true;
                }
                return false;

            }).WithMessage("非法BuyerUserId");
            RuleFor(x => x.SellerUserId).Must(x => CommonValidator.IsUserInShop(x))
                .WithMessage("非法SellerUserId");
            RuleFor(x => x.Amount).Must(x => RegExpTool.IsOrderAmount(x))
                .WithMessage("非法Amount");
        }

        private bool IsOrderIdValiad(int orderId)
        {
            var hour = DateTime.Now.Hour;
            if (!(hour >= 15 && hour <= 23))
            {
                return false;
            }

            var userService2 = GetIUserService2();
            var ui = userService2.GetLoginUser();
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            var orderService = GetOrderService();
            bool bSuccess = orderService.IsOrderIdValid(
                                 orderId
                                 , date
                                 , ui.Id
                            );
            return bSuccess;
        }
    }
}